<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools title="总记录数据20条">
        <!-- <el-button
          type="warning"
          size="small"
          @click="$router.push('/import')"
        >excel{{ $t('route.import') }}</el-button>
        <el-button
          type="danger"
          size="small"
          @click="hExportExcel"
        >excel导出</el-button>
        <el-button
          type="primary"
          size="small"
          @click="showDialog = true"
        >新增员工</el-button> -->
        <!-- v-if="$store.state.user.userInfo.roles.points.includes('import_excel')" -->
        <el-button
          v-allow="'import_excel'"
          type="warning"
          size="small"
          @click="$router.push('/import')"
        >excel {{ $t('route.import') }}</el-button>
        <el-button
          v-allow="'export_excel'"
          type="danger"
          size="small"
          @click="hExportExcel"
        >
          <!-- 如果vuex中points有 “export_excel” 就创建按钮 -->
          excel导出
        </el-button>
        <!-- v-allow="'add_employee'" -->
        <el-button type="primary" size="small" @click="showDialog = true">
          新增员工
        </el-button>
      </PageTools>
      <el-card style="margin-top: 10px">
        <el-table
          border
          :data="employee"
          :default-sort="{ prop: 'workNumber' }"
        >
          <el-table-column
            type="index"
            label="序号"
            :index="(pageParams.page - 1) * pageParams.size + 1"
          />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
              >{{ $t('table.view') }}</el-button>
              <el-button
                type="text"
                size="small"
                @click="hAssignRole(scope.row.id)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页组件
                current-change: 翻页时执行回调
                size-change : 每页几条 改变执行
                total : 一共有几条数据
                current-page : 当前的页码
                page-size  : 每页显示几条
                page-sizes : 可以自己选择的 每页几条数据
                layout : 整体的布局
                @current-change : 跳转页码事件
                @size-change: 修改每页几条时事件
              -->
          <el-pagination
            :total="total"
            :current-page="pageParams.page"
            :page-size="pageParams.size"
            :page-sizes="[2, 5, 10, 20]"
            layout="total,sizes,prev,pager,next,jumper"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hClose"
    >
      <!-- <EmpDialog v-if="showDialog" @success="hSuccess" /> -->
      <EmpDialog ref="empDialog" @success="hSuccess" />
    </el-dialog>
    <el-dialog
      :visible.sync="showDialogRole"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <assign-role v-if="showDialogRole" :cur-id="curId" @close="assSuccess" />
    </el-dialog>
  </div>
</template>

<script>
import AssignRole from './assignRole.vue'
import EmpDialog from './empDialog.vue'
import { TYPE_MAP } from '@/constant/index'
import { getEmployeeList, delEmployee } from '@/api/employees'
export default {
  components: { EmpDialog, AssignRole },
  data() {
    return {
      showDialog: false,
      pageParams: { page: 1, size: 10 },
      employee: [],
      total: 0,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.getEmployee()
    setTimeout(() => {
      this.$i18n.locale = 'zh'
    }, 3000)
  },
  methods: {
    assSuccess() {
      this.showDialogRole = false
    },
    hAssignRole(id) {
      // console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.curId = id
    },
    // rows: [{mobile:'13600000001', usename:'吕勇锐'}, {mobile:'13600000002', usename:'袁永安'}]
    //
    // data:
    //  [
    //   ["13600000001", "吕勇锐"]
    //   ["13600000002", "袁永安"]
    //  ]
    formatData(rows) {
      // 表头
      // 英文的表头['mobile', 'usename']，要转换成中文的 ['手机号', '用户名']
      const enHeader = Object.keys(rows[0])

      const mapObj = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      const header = enHeader.map((en) => mapObj[en])

      // 内容
      const data = rows.map((obj) => {
        // 把聘用格式进行转换
        // obj.formOfEmployment ====> 1, 2
        obj.formOfEmployment = TYPE_MAP[obj.formOfEmployment]
        return Object.values(obj)
      })

      return { header, data }
    },
    async hExportExcel() {
      // 1. 发请求拿数据
      const res = await getEmployeeList(this.pageParams)
      // 2. 对数据进行格式转换
      const { header, data } = this.formatData(res.data.rows)
      // 3. 导出
      console.log('员工信息', header, data)

      import('@/vendor/Export2Excel').then((excel) => {
        // 准备数据
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)

        // 生成excel
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hClose() {
      // 清空子组件的表单数据 &校验结果
      // 思路: 在子组件内部提供一个方法,在父组件调用
      this.$refs.empDialog.resetForm()
    },
    // 子组件添加成功
    hSuccess() {
      // 关闭弹层
      this.showDialog = false
      // 更新数据
      this.getEmployee()
      // this.$refs.empDialog.resetForm()
    },
    // 删除 函数
    async doDel(id) {
      try {
        // 1.删除
        await delEmployee(id)
        // 2. 提示
        this.$message.success('删除成功')
        // 3.重发请求
        // 判断是否表格中只有一条数据 && 页码 > 1
        if (this.employee.length === 1 && this.pageParams.page > 1) {
          this.pageParams.page--
        }
        this.getEmployee()
      } catch (error) {
        console.log(error)
      }
    },
    // 用户点击删除
    async hDel(id) {
      try {
        await this.$confirm('确定要删除吗?', '系统提示')
        this.doDel(id)
      } catch (error) {
        console.log('删除失败', error)
      }
      // // 提示确认删除吗?
      // this.$confirm('确定删除吗?', '系统提示')
      //   .then(() => {
      //     this.doDel(id)
      //   })
      //   .catch(() => {})
    },
    format(type) {
      return TYPE_MAP[type] || '未知'
    },
    async getEmployee() {
      const res = await getEmployeeList(this.pageParams)
      console.log(res)
      this.total = res.data.total
      this.employee = res.data.rows
    },
    // 会自动接收当前点击的页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.pageParams.page = curPage
      // 2. 重发请求
      this.getEmployee()
    },
    // 每页几条
    hSizeChange(curSize) {
      // alert(size)
      // 1. 更新每页的条数
      this.pageParams.size = curSize
      // 2. 重发请求
      this.getEmployee()
      console.log('1')
    }
  }
}
</script>

<style></style>
